/**
 * Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// @ts-nocheck
import rime from 'librime.so';
import system from '@system.app'
import display from '@ohos.display'
import window from '@ohos.window'
import {InputMethodEngine} from '@ohos.inputMethodEngine'

var inputMethodEngine = new InputMethodEngine();

// @ts-ignore
var rimeEngine = rime.getRimeEngine();

var deleteCode = 65288
var nextCode = 65366
var prevCode = 65365

export default {
  data: {
    wordList: [
      {
        title: '1',
        content: 'q',
        upperContent: 'Q',
        keyCode: 113
      },
      {
        title: '2',
        content: 'w',
        upperContent: 'W', keyCode: 119
      },
      {
        title: '3',
        content: 'e',
        upperContent: 'E', keyCode: 101
      },
      {
        title: '4',
        content: 'r',
        upperContent: 'R', keyCode: 114
      },
      {
        title: '5',
        content: 't',
        upperContent: 'T', keyCode: 116
      },
      {
        title: '6',
        content: 'y',
        upperContent: 'Y', keyCode: 121
      },
      {
        title: '7',
        content: 'u',
        upperContent: 'U', keyCode: 117
      },
      {
        title: '8',
        content: 'i',
        upperContent: 'I', keyCode: 105
      },
      {
        title: '9',
        content: 'o',
        upperContent: 'O', keyCode: 111
      },
      {
        title: '0',
        content: 'p',
        upperContent: 'P', keyCode: 112
      },
      {
        title: String.fromCharCode(126),
        content: 'a',
        upperContent: 'A', keyCode: 97
      },
      {
        title: String.fromCharCode(33),
        content: 's',
        upperContent: 'S', keyCode: 115
      },
      {
        title: '@',
        content: 'd',
        upperContent: 'D', keyCode: 100
      },
      {
        title: String.fromCharCode(35),
        content: 'f',
        upperContent: 'F', keyCode: 102
      },
      {
        title: '%',
        content: 'g',
        upperContent: 'G', keyCode: 103
      },
      {
        title: '”',
        content: 'h',
        upperContent: 'H', keyCode: 104
      },
      {
        title: '"',
        content: 'j',
        upperContent: 'J', keyCode: 106
      },
      {
        title: '*',
        content: 'k',
        upperContent: 'K', keyCode: 107
      },
      {
        title: '?',
        content: 'l',
        upperContent: 'L', keyCode: 108
      },
      {
        title: '(',
        content: 'z',
        upperContent: 'Z', keyCode: 122
      },
      {
        title: ')',
        content: 'x',
        upperContent: 'X', keyCode: 120
      },
      {
        title: String.fromCharCode(175),
        content: 'c',
        upperContent: 'C', keyCode: 99
      },
      {
        title: String.fromCharCode(95),
        content: 'v',
        upperContent: 'V', keyCode: 118
      },
      {
        title: String.fromCharCode(58),
        content: 'b',
        upperContent: 'B', keyCode: 98
      },
      {
        title: String.fromCharCode(59),
        content: 'n',
        upperContent: 'N', keyCode: 110
      },
      {
        title: String.fromCharCode(47),
        content: 'm',
        upperContent: 'M', keyCode: 109
      }
    ],
    numberSymbolList: [
      {
        content: '1'
      },
      {
        content: '2'
      },
      {
        content: '3'
      },
      {
        content: '4'
      },
      {
        content: '5'
      },
      {
        content: '6'
      },
      {
        content: '7'
      },
      {
        content: '8'
      },
      {
        content: '9'
      },
      {
        content: '0'
      },
      {
        content: '-'
      },
      {
        content: '/'
      },
      {
        content: ':'
      },
      {
        content: ';'
      },
      {
        content: '('
      },
      {
        content: ')'
      },
      {
        content: '['
      },
      {
        content: ']'
      },
      {
        content: '@'
      },
      {
        content: String.fromCharCode(39)
      },
      {
        content: '...'
      },
      {
        content: '~'
      },
      {
        content: '`'
      },
      {
        content: '?'
      },
      {
        content: '!'
      },
      {
        content: '—'
      },
      {
        content: '.'
      }
    ],
    symbolList: [
      {
        content: '【'
      },
      {
        content: '】'
      },
      {
        content: '{'
      },
      {
        content: '}'
      },
      {
        content: '#'
      },
      {
        content: '%'
      },
      {
        content: '^'
      },
      {
        content: '*'
      },
      {
        content: '+'
      },
      {
        content: '='
      },
      {
        content: '_'
      },
      {
        content: '\\'
      },
      {
        content: '|'
      },
      {
        content: '《'
      },
      {
        content: '》'
      },
      {
        content: '¥'
      },
      {
        content: '$'
      },
      {
        content: '&'
      },
      {
        content: '·'
      },
      {
        content: String.fromCharCode(39)
      }
    ],
    status: 1,
    oldStatusArrs: [],
    isKeyBoardShow: false,
    isEntering: false,
    enteringText: '',
    resultList: [],
    pageIndex: 1,
    localEngText: '',
    isShowDialog: false,
    dialogText: '',
    dialogShowSeconds: 3,
    writeWidth: 0,
    writeHeight: 0,
    itemData: {},
    itemRect: {},
    isShowSelectContainer: false,
    isShowVoice: false,
    isLast: 0,
    keyboardHeight: 47.4
  },

  onInit() {
    let that = this;

    display.getDefaultDisplay().then(function (dis) {
      that.writeWidth = dis.width;
      that.writeHeight = dis.height;
      var x = 0.75
      if (dis.width < dis.height) {
        x = 1.25
      }
      var itemHeight = dis.width * 0.98 * 0.09 * x / 0.8
      that.keyboardHeight = itemHeight * 5.4

      var navigationbarHeight = that.writeHeight * 0.07;

      window.getTopWindow().then(function (windowData) {
        windowData.resetSize(dis.width, that.keyboardHeight);
        windowData.moveTo(0, that.writeHeight - that.keyboardHeight - navigationbarHeight);
      });
    });

    inputMethodEngine.on('keyboardShow', (err) => {
      that.initChineseIme()
    });

    inputMethodEngine.on('keyboardHide', (err) => {
      rimeEngine.rimeClose((error, isClose) => {
      })
      that.isKeyBoardShow = false;
      that.appExit();
    });
  },

  initChineseIme() {
    this.isKeyBoardShow = true;
    rimeEngine.rimeOpen((error, isOpen) => {
      if (isOpen) {
        this.isKeyBoardShow = isOpen;
      } else {
        this.showDialog('中文输入法初始化失败');
      }
    })
  },

  showDialog(content) {
    this.isShowDialog = true
    this.dialogText = content
    setTimeout(this.hideDialog, 3000)
  },

  hideDialog() {
    this.isShowDialog = false
    this.dialogText = ''
  },

  submitWord(e) {
    if (this.status === 1) {
      var word = e.detail.word;
      this.getChineseResultList(word.keyCode);
    } else if (this.status === 3) {
      inputMethodEngine.insertText(e.detail.word)
    }
  },

  getChineseResultList(keyCode) {
    rimeEngine.rimeHandleKey(keyCode, (error, isSuccess) => {
      if (isSuccess) {
        if (keyCode === prevCode) {
          this.pageIndex -= 1
        } else if (keyCode === nextCode) {
          this.pageIndex += 1
        } else if (keyCode === deleteCode && this.enteringText.length === 1) {
          this.resetEnterAndWordResult()
          this.setIsInputWord();
          return
        }
        rimeEngine.rimeGetComposition((error, string) => {
          this.enteringText = string.replace(/ /g, String.fromCharCode(39));
          this.setIsInputWord();
          rimeEngine.rimeGetCandidate((error, result) => {
            this.isLast = result.isLast
            this.resultList = [];
            for (var i = 0;i < result.resultList.length; i++) {
              var item = {
                index: i, content: result.resultList[i]
              }
              this.resultList.push(item)
            }
          });
        });
      } else {
        this.showDialog('出错啦');
      }
    });
  },

  submitNumberOrSymbol(e) {
    if (this.status === 1) {
      if (this.isEntering) {
        if (this.resultList.length > 0) {
          var _item = {
            detail: {
              selectWord: this.resultList[0]
            }
          }
          this.selectWord(_item)
        } else {
          this.resetEnterAndWordResult();
        }
      }
      inputMethodEngine.insertText(e.detail.word)
    } else if (this.status === 3 || this.status === 4
    || this.status === 5 || this.status === 6 || this.status === 7) {
      inputMethodEngine.insertText(e.detail.word)
    }
  },

  deleteWord() {
    if (this.status === 1) {
      if (this.isEntering) {
        this.getChineseResultList(deleteCode)
      } else {
        inputMethodEngine.DeleteBackward(1);
      }
    } else if (this.status === 2 || this.status === 3 || this.status === 4
    || this.status === 5 || this.status === 6 || this.status === 7) {
      inputMethodEngine.DeleteBackward(1);
    }
  },

  selectWord(e) {
    var item = e.detail.selectWord;
    if (this.status == 1 || this.status == 2) {
      rimeEngine.rimeChooseCandidateOnCurrentPage(e.detail.selectWord.index, (error, isSuccess) => {
        inputMethodEngine.insertText(item.content)
        this.resetEnterAndWordResult();
      })
    } else if (this.status == 7) {
      inputMethodEngine.insertText(item.content)
      this.resetEnterAndWordResult();
      this.resetCanves();
    }
  },

  changeKeyboardType(e) {
    this.oldStatusArrs.push(this.status)
    this.changeType(e.detail.status)
  },

  changeType(nowStatus) {
    if (nowStatus != 2 || !(nowStatus === 1 && this.status === 2)) {
      this.resetEnterAndWordResult()
    }
    this.status = nowStatus;
  },

  changePage(e) {
    var code = e.detail.code
    this.getChineseResultList(code)
  },

  down() {
    inputMethodEngine.HideKeyboardSelf();
  },

  resetEnterAndWordResult() {
    this.isEntering = false;
    this.enteringText = '';
    this.localEngText = '';
    this.resetResultList();
  },

  resetResultList() {
    this.resultCount = 0;
    this.pageIndex = 1;
    this.isLast = 0;
    this.resultList = [];
  },

  setIsInputWord() {
    if (this.enteringText.length > 0) {
      this.isEntering = true;
    } else {
      this.isEntering = false;
    }
  },

  back() {
    this.changeType(this.oldStatusArrs[this.oldStatusArrs.length-1])
    this.oldStatusArrs.splice(this.oldStatusArrs.length - 1, 1)
  },

  appExit() {
    system.terminate();
  },

  longPress(e) {
    this.itemData = e.detail.itemData;
    this.itemRect = e.detail.itemRect;
    let width = 3 * this.itemRect.width
    let height = this.itemRect.height
    let left = this.itemRect.left - (width - this.itemRect.width) / 2.00
    let top = this.itemRect.top - height - 8
    this.itemRect.width = width;
    this.itemRect.height = height;
    this.itemRect.left = left;
    this.itemRect.top = top;
    this.isShowSelectContainer = true;
  },

  select(type, val) {
    let e = {
      detail: {
        word: val
      }
    }
    if (type === 1) {
      this.submitWord(e)
    } else {
      this.submitNumberOrSymbol(e)
    }
    this.isShowSelectContainer = false;
    this.itemData = {};
    this.itemRect = {};
  },
}